package url

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"net/url"
	"time"
	"encoding/json"
	"bytes"
)
// get 网络请求
func Get(apiURL string,params url.Values)(rs[]byte ,err error){
	var Url *url.URL
	Url,err=url.Parse(apiURL)
	if err!=nil{
		fmt.Printf("解析url错误:\r\n%v",err)
		return nil,err
	}
	//如果参数中有中文参数,这个方法会进行URLEncode
	Url.RawQuery=params.Encode()
	resp,err:=http.Get(Url.String())
	if err!=nil{
		//fmt.Println("err:",err)
		return nil,err
	}
	defer resp.Body.Close()
	//fmt.Println("hhh",resp.StatusCode)
	return ioutil.ReadAll(resp.Body)
}

//// post 网络请求 ,params 是url.Values类型
func Post(apiURL string, params url.Values)(rs[]byte,err error){
	resp,err:=http.PostForm(apiURL, params)
	if err!=nil{
		return nil ,err
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}
// post 网络请求 ,params 是url.Values类型
func PostS(apiURL string, param interface{},try int)(*http.Response, error){
	var jsonstr []byte
	if param!=nil {
		tmp,err := json.Marshal(param)
		jsonstr=tmp
		if err != nil {
			return nil,err
		}
	}
	req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonstr))
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	client.Timeout=time.Second*10
	resp, err := client.Do(req)
	if err != nil {
		return nil,err;
	}
	if resp.StatusCode!=http.StatusOK{
		for i:=0;i<try ;i++  {
			resp, err := client.Do(req)
			if err != nil && resp.StatusCode==http.StatusOK{
				break
			}

		}
	}
	defer resp.Body.Close()
	return resp,err

}